<?php

namespace app\api\controller;


use app\admin\model\LevelBuyLog;
use app\common\controller\Api;
use app\admin\model\UserLevelSetting;
use app\admin\model\LevelDetail;
use think\Db;
use think\Exception;


/**
 * 用户等级
 */
class UserLevel extends Api
{

    protected $noNeedLogin = ['level_list', 'level_detail'];
    protected $noNeedRight = ['*'];

    /**
     * 等级列表
     * @ApiTitle    (等级列表)
     * @ApiSummary  (等级列表)
     */
    public function level_list()
    {
        //$res = UserLevelSetting::with(['leveldetail'])->select();
        $userLevelList = UserLevelSetting::select();
        $this->success('ok', $userLevelList);

    }

    /**
     * 等级详情
     */
    public function level_detail()
    {
        $level_detail_ids = input("level_detail_ids");

        if (empty($level_detail_ids)) {
            $this->error('请输入用户等级详情ID');
        }
        $detailList = LevelDetail::where(['status' => 1])->whereIn('id',$level_detail_ids)->select();
        $this->success('获取成功', $detailList);
    }

    /**
     * 用户等级购买
     */
    public function user_level_buy()
    {
        $unfreeze_day = config("site.unfreeze_day");
        $level_id = input("level_id");
        if (empty($level_id)) {
            $this->error("请输入等级ID");
        }
        $user = \app\admin\model\User::where(['id' => $this->auth->id])->find();
//        if($user['level']+1!=$level_id){
//            $this->error('不可越级升级');
//        }
        $dj_score = 'level'.$level_id.'_dj_score';
        $current_level = 'level'.$user['level'].'_dj_score';
        //获取等级设置
        $userLevelSetting = UserLevelSetting::where(['level' => $level_id])->find();
        if ($user->money < $userLevelSetting['level_price']) {
            $this->error('当前余额不足');
        }
        Db::startTrans();
        try {
            $level_buy_log = [
                'user_id' => $this->auth->id,
                'level' => $level_id,
                'money' => $userLevelSetting->level_price,
                'type' => 2,
                'ctime' => time(),
                'award_score' => $userLevelSetting->award_score
            ];
            $buy_log = LevelBuyLog::create($level_buy_log);
            //用户余额记录
            $user_money_log = [
                'user_id' => $this->auth->id,
                'money' => -$userLevelSetting->level_price,
                'before' => $user->money,
                'after' => bcsub($user->money, $userLevelSetting->level_price, 2),
                'memo' => '会员购买',
                'createtime' => time()
            ];
            Db::name('user_money_log')->insert($user_money_log);
            //减去购买会员的余额
            Db::name('user')->where(['id' => $this->auth->id])->setDec('money', $userLevelSetting->level_price);
            //购买奖励的积分 用户积分记录

            $before = bcsub($user->score,$user->$current_level,2);
            //奖励的积分乘以倍数
            $award_score = bcmul($userLevelSetting->award_score,$userLevelSetting->mom);
            $user_score_log = [
                'user_id' => $this->auth->id,
                'score' => $award_score,
                'before' => $before,
                'after' => bcadd($before, $award_score),
                'memo' => '会员购买奖励积分',
                'createtime' => time()
            ];
            Db::name('user_score_log')->insert($user_score_log);
            //增加奖励的积分
            Db::name('user')->where(['id' => $this->auth->id])->setInc('score', $award_score);
            //是否有冻结的积分
            if ($userLevelSetting->freeze_score > 0) {
                //每天释放的数量
                $days_unfreeze = bcdiv($userLevelSetting->freeze_score, $unfreeze_day);
                //写冻结记录表
                $score_freeze_log = [
                    'user_id' => $this->auth->id,
                    'unfreeze' => $userLevelSetting->freeze_score,
                    'type' => 1,
                    'remark' => '用户购买等级' . $userLevelSetting->level . '冻结积分',
                    'freeze_day' => $unfreeze_day,  //冻结的天数，
                    'released_day' => 0,
                    'status' => 1,
                    'ctime' => time(),
                    'days_unfreeze' => $days_unfreeze,
                    'source' => $buy_log->id
                ];
                Db::name('score_freeze_log')->insert($score_freeze_log);
                //增加用户冻结的积分
                Db::name('user')->where(['id' => $this->auth->id])->setInc($dj_score, $userLevelSetting->freeze_score);
                $before = bcsub($user->score,$user->$current_level,2);
                //购买奖励的积分后 冻结积分
                $user_score_log = [
                    'user_id' => $this->auth->id,
                    'score' => -$userLevelSetting->freeze_score,
                    'before' => $before,
                    'after' => bcsub($before, $userLevelSetting->freeze_score),
                    'memo' => '会员购买冻结等级'.$level_id.'积分',
                    'createtime' => time()
                ];
                Db::name('user_score_log')->insert($user_score_log);
            }
            //冻结的积分是否解冻
            if($userLevelSetting->unfreeze==1){
                Db::name('user')->where(['id'=>$this->auth->id])->setDec("$current_level",$user->$current_level);
                //增加解冻记录
                $user_score_log = [
                    'user_id' => $this->auth->id,
                    'score' => $user->$current_level,
                    'before' => $before,
                    'after' => bcadd($before, $user->$current_level),
                    'memo' => '冻结的上一级积分解冻',
                    'createtime' => time()
                ];
                Db::name('user_score_log')->insert($user_score_log);
            }
            Db::name('user')->where(['id'=>$this->auth->id])->update(['level'=>$level_id]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('购买成功');
    }
}
